<template>
  <div>
    <van-nav-bar fixed title="城市列表">
      <template #left>
        <van-icon color="#fff" name="arrow-left" @click="$router.back()" />
      </template>
    </van-nav-bar>
    <div class="citys">
      <van-index-bar
        :index-list="indexList"
        z-index="0"
        highlight-color="green"
      >
        <van-index-anchor index="当前城市" />
        <van-cell :title="currentCity.city" />

        <van-index-anchor index="热门城市" />
        <van-cell
          @click="gohome(item)"
          :title="item.label"
          v-for="item in hotlist"
          :key="item.label"
        />

        <div v-for="(value, key) in shortcity" :key="key">
          <van-index-anchor :index="key.toUpperCase()" />
          <van-cell
            :title="item.label"
            v-for="(item, index) in value"
            :key="index"
            @click="gohome(item)"
          />
        </div>
      </van-index-bar>
    </div>
  </div>
</template>

<script>
import { hotscity, getcity } from '@/api/city'
import { mapState, mapMutations } from 'vuex'

export default {
  data () {
    return {
      hotlist: [],
      citys: []
    }
  },

  created () {
    this.gethotcity()
    this.getCity()
  },
  computed: {
    ...mapState(['currentCity']),
    shortcity () {
      const arr = this.citys.map((item) => {
        return item.short[0]
      })
      const arr1 = [...new Set(arr)]
      const obj = {}
      arr1.sort()
      arr1.forEach((item) => {
        obj[item] = []
      })
      this.citys.forEach((item) => {
        obj[item.short[0]].push(item)
      })
      return obj
    },
    indexList () {
      const arr = this.citys.map((item) => {
        return item.short[0]
      })
      const arr1 = [...new Set(arr)]
      arr1.sort()
      const arr2 = arr1.map((item) => item.toUpperCase())
      arr2.unshift('#', '热')
      return arr2
    }
  },
  methods: {
    ...mapMutations(['setCity']),
    gohome (item) {
      this.setCity({
        city: item.label,
        id: item.value
      })
      this.$router.back()
    },
    async gethotcity () {
      try {
        const res = await hotscity()
        this.hotlist = res.data.body
      } catch (err) {
        console.log(err.message)
      }
    },
    async getCity () {
      try {
        const res = await getcity(1)
        this.citys = res.data.body
      } catch (err) {
        console.log(err.message)
      }
    }
  }
}
</script>

<style scoped lang="less">
.citys {
  padding-top: 50px;
  /deep/.van-index-anchor {
    font-size: 14px;
    padding: 10px 15px;
    color: #999;
  }
  /deep/.van-index-bar__index {
    margin: 5px;
    padding: 0;
    width: 15px;
    height: 15px;
    text-align: center;
    line-height: 15px;
    border-radius: 50%;
  }
  /deep/.van-index-bar__index--active {
    color: #fff;
    background-color: #21b97a;
  }
}
</style>
